<!--  -->
<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>

    <el-card class="box-card">
      <el-row>
        <el-col>
          <el-button type="primary" @click="addDialogVisible = true"
            >添加用户</el-button
          >
        </el-col>
      </el-row>
      <el-table :data="rolesList" stripe border>
        <el-table-column type="expand">
          <template slot-scope="scope">
            <el-row
              v-for="(item1, index1) in scope.row.children"
              :key="item1.id"
              :class="['bottomLine', index1 === 0 ? 'topLine' : '', 'vcenter']"
            >
              <el-col :span="5">
                <el-tag closable @close="removeTag(scope.row, item1.id)">{{
                  item1.authName
                }}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>

              <el-col :span="19">
                <el-row
                  v-for="(item2, index2) in item1.children"
                  :key="item2.id"
                  :class="[index2 === 0 ? '' : 'topLine', 'vcenter']"
                >
                  <el-col :span="6">
                    <el-tag
                      closable
                      type="success"
                      @close="removeTag(scope.row, item2.id)"
                      >{{ item2.authName }}</el-tag
                    >
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <el-col :span="18">
                    <el-tag
                      v-for="item3 in item2.children"
                      :key="item3.id"
                      closable
                      type="warning"
                      @close="removeTag(scope.row, item3.id)"
                      >{{ item3.authName }}</el-tag
                    >
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column
          type="index"
          label="序号"
          width="50px"
        ></el-table-column>
        <el-table-column prop="roleName" label="角色名称"></el-table-column>
        <el-table-column prop="roleDesc" label="角色描述"> </el-table-column>
        <el-table-column prop="" label="操作">
          <template slot-scope="scope">
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click="showEditorDialog(scope.row.id)"
              >编辑</el-button
            >
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="deleteRole(scope.row.id)"
              >删除</el-button
            >

            <el-button
              type="warning"
              icon="el-icon-setting"
              size="mini"
              @click="showDistrDialog(scope.row)"
              >分配权限</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <el-dialog
      title="添加用户"
      :visible.sync="addDialogVisible"
      width="50%"
      @close="addDialogClose"
    >
      <el-form
        ref="addFormRef"
        :model="addForm"
        label-width="80px"
        :rules="addFormRules"
      >
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="addForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述">
          <el-input v-model="addForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addRole">确 定</el-button>
      </span>
    </el-dialog>

    <el-dialog
      title="编辑用户"
      :visible.sync="editorDialogVisible"
      width="50%"
      @close="editorDialogClose"
    >
      <el-form
        ref="editorFormRef"
        :model="editorForm"
        label-width="80px"
        :rules="editorFormRules"
      >
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="editorForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述">
          <el-input v-model="editorForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editorDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editorRole">确 定</el-button>
      </span>
    </el-dialog>

    <el-dialog title="分配权限" :visible.sync="distrDialogVisible" width="50%">
      <el-tree
        ref="treeRef"
        :data="rightList"
        :props="defaultProps"
        show-checkbox
        default-expand-all
        node-key="id"
        :default-checked-keys="keysList"
      ></el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="distrDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="distrRoles">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'Roles',
  data () {
    return {
      rolesList: [],
      addForm: {
        roleName: '',
        roleDesc: ''
      },
      addDialogVisible: false,
      addFormRules: {
        roleName: [
          { required: true, message: '请输入权限名称', trigger: 'blur' }
        ]
      },
      editorDialogVisible: false,
      editorForm: {
        roleId: '',
        roleName: '',
        roleDesc: ''
      },
      editorFormRules: {
        roleName: [
          { required: true, message: '请输入权限名称', trigger: 'blur' }
        ]
      },
      distrDialogVisible: false,
      rightList: [],
      defaultProps: {
        children: 'children',
        label: 'authName'
      },
      keysList: [],
      roleId: ''
    }
  },

  components: {},

  methods: {
    async getRolesList () {
      const { data } = await this.$http.get('roles')
      if (data.meta.status !== 200) { return this.$message.error('获取权限数据失败！') }
      this.rolesList = data.data
    },
    async removeTag (role, rightId) {
      const deleteConfirm = await this.$confirm(
        '此操作将永久删除该权限, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch(err => err)
      // console.log(deleteConfirm);
      if (deleteConfirm !== 'confirm') { return this.$message.info('已取消删除该权限！') }
      const { data } = await this.$http.delete(
        `roles/${role.id}/rights/${rightId}`
      )
      if (data.meta.status !== 200) { return this.$message.error('删除权限失败！') }
      this.$message.success('删除权限成功！')
      role.children = data.data
    },
    addDialogClose () {
      this.$$refs.addFormRef.resetFields()
    },
    addRole () {
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) return
        const { data } = await this.$http.post('roles', this.addForm)
        console.log(data)
        if (data.meta.status !== 201) { return this.$message.error('添加用户失败!') }
        this.$message.success('添加用户成功！')
        this.addDialogVisible = false
        this.getRolesList()
      })
    },
    editorDialogClose () {
      this.$refs.editorFormRef.resetFields()
    },
    async showEditorDialog (id) {
      const { data } = await this.$http.get('roles/' + id)
      if (data.meta.status !== 200) { return this.$message.error('获取数据失败！') }
      this.editorForm = data.data
      this.editorDialogVisible = true
    },
    editorRole () {
      this.$refs.editorFormRef.validate(async valid => {
        if (!valid) return
        const { data } = await this.$http.put(
          'roles/' + this.editorForm.roleId,
          {
            roleName: this.editorForm.roleName,
            roleDesc: this.editorForm.roleDesc
          }
        )
        // console.log(data);
        if (data.meta.status !== 200) { return this.$message.error('编辑用户失败!') }
        this.$message.success('编辑用户成功！')
        this.editorDialogVisible = false
        this.getRolesList()
      })
    },
    async deleteRole (id) {
      const deleteConfirm = await this.$confirm(
        '此操作将永久删除该角色, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch(err => err)
      // console.log(deleteConfirm);
      if (deleteConfirm !== 'confirm') { return this.$message.info('已取消删除该角色！') }
      const { data } = await this.$http.delete('roles/' + id)
      if (data.meta.status !== 200) { return this.$message.error('删除该角色失败！') }
      // this.editorDialogVisible = false
      this.$message.success('删除用户成功！')
      this.getRoleList()
    },
    async showDistrDialog (role) {
      this.keysList = []
      this.roleId = role.id
      const { data } = await this.$http.get('rights/tree')
      if (data.meta.status !== 200) { return this.$message.error('获取权限列表失败！') }
      this.rightList = data.data
      this.findKeys(role, this.keysList)
      console.log(role)
      console.log(this.keysList)
      this.distrDialogVisible = true
    },
    async distrRoles () {
      const arr = [
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys()
      ]
      const str = arr.join(',')
      const { data } = await this.$http.post(`roles/${this.roleId}/rights`, {
        rids: str
      })
      if (data.meta.status !== 200) return this.$message.error('权限分配失败！')
      this.$message.success('权限分配成功！')
      this.distrDialogVisible = false
      this.getRolesList()
    },
    findKeys (node, arr) {
      if (!node.children) {
        return arr.push(node.id + '')
      }
      node.children.forEach(item => {
        this.findKeys(item, arr)
      })
    }
  },
  created () {
    this.getRolesList()
  }
}
</script>
<style scoped>
.bottomLine {
  border-bottom: 1px solid #eee;
}
.topLine {
  border-top: 1px solid #eee;
}
.vcenter {
  display: flex;
  align-items: center;
}
.el-tag {
  margin: 7px;
}
</style>
